<?php

/**
 * Gestisce tutte le richieste Ajax - LaFabbrica.org
 *
 * @created 21-mag-2011
 * @author     luigi.pastore (gigi@la-fabbrica.org)
 * @package    LaFabbrica
 * @copyright  Copyright (c) 2011 Luigi Pastore
 */
class AjaxController extends Classes_Controller
{

    public function init()
    {
	$this->layout->disableLayout( true );

	// Parametri della richiesta
	$this->params = $this->getParams();
    }

    /**
     * Elenchi.
     * Sceglie la sezione in base al parametro 'section' passato da url
     * Eg: /ajax/list/posts/param1/value1/param2/value2 ...
     * 
     * selected è nel formato "/selected/id1:id2:id3"
     * 
     * In generale rimanda a listSezione() per elenchi standard (archivio, rubriche, ecc..
     * e a listSezioneMini per elenchi ridotti (layout a due colonne, ecc..)
     */
    public function listAction()
    {

	if( empty( $this->params['section'] ) )
	    throw new Classes_Exceptions( 'Ajax: URL malformato' );

	switch( $this->params['section'] )
	{
	    case 'posts':
		return $this->listPosts();
		break;

	    case 'users':
		return $this->listUsers();
		break;

	    case 'locations':
		return $this->listLocations();
		break;

	    case 'contacts':
		return $this->listContacts();
		break;

	    case 'contactsmini':
		return $this->listContactsMini();
		break;

	    case 'partners':
		return $this->listPartners();
		break;

            case 'partnersmini':
		return $this->listPartnersMini();
		break;

	    case 'live':
		return $this->listLive();
		break;

	    case 'booking-live':
		return $this->listBookingLive();
		break;

	    case 'booking-events':
		return $this->listBookingEvents();
		break;

	    case 'booking-activities':
		return $this->listBookingActivities();
		break;

	    case 'artistsmini':
		return $this->listArtistsMini();
		break;

	    case 'locationsmini':
		return $this->listLocationsMini();
		break;

	    case 'events':
		return $this->listEvents();
		break;

	    case 'eventsmini':
		return $this->listEventsMini();
		break;

            case 'tourbooks':
                return $this->listTourbooks();
                break;
	    default:
		break;
	}
	//sleep(2);
    }

    /**
     * Elenco Post
     */
    private function listPosts()
    {
	$this->model_post = new Classes_Post();

	list( $orderby_field, $orderby_dir ) = explode( ':', $this->params['orderby'] );

	//
	$per_page = $this->params['per_page']; //rows per page
	$start = ( $this->params['page'] - 1 ) * $per_page;

	$this->layout->posts = $this->model_post->fetchAll( array(
		    'orderby' => array( $orderby_field => $orderby_dir ),
		    'limit' => array( $start, $per_page )
			)
	);

	$this->layout->pages = ceil( count( $this->layout->posts ) / $per_page );

	$this->layout->content = array( 'script' => 'ajax/list/posts' );
    }

    /**
     * Elenco Utenti
     */
    private function listUsers()
    {
	$this->model_user = new Classes_Users;

	list( $orderby_field, $orderby_dir ) = explode( ':', $this->params['orderby'] );

	//
	$per_page = $this->params['per_page']; //rows per page
	$start = ( $this->params['page'] - 1 ) * $per_page;

	$this->layout->users = $this->model_user->fetchAll( array(
		    'orderby' => array( $orderby_field => $orderby_dir ),
		    'limit' => array( $start, $per_page )
			)
	);

	$this->layout->pages = ceil( count( $this->layout->users ) / $per_page );

	$this->layout->content = array( 'script' => 'ajax/list/users' );
    }

    /**
     * Elenco Locations
     */
    private function listLocations()
    {
	$this->model_location = new Classes_Location();

	list( $orderby_field, $orderby_dir ) = explode( ':', $this->params['orderby'] );

	//
	$per_page = $this->params['per_page']; //rows per page
	$start = ( $this->params['page'] - 1 ) * $per_page;

	$this->layout->locations = $this->model_location->fetchAll( array(
		    'orderby' => array( $orderby_field => $orderby_dir ),
		    'limit' => array( $start, $per_page )
			)
	);

	$this->layout->pages = ceil( count( $this->layout->locations ) / $per_page );

	$this->layout->content = array( 'script' => 'ajax/list/locations' );
    }

    /**
     * Elenco Contatti
     */
    private function listContacts()
    {
	$this->model_contact = new Classes_Contact();

	list( $orderby_field, $orderby_dir ) = explode( ':', $this->params['orderby'] );

	//
	$per_page = $this->params['per_page']; //rows per page
	$start = ( $this->params['page'] - 1 ) * $per_page;

	$this->layout->contacts = $this->model_contact->fetchAll( array(
		    'orderby' => array( $orderby_field => $orderby_dir ),
		    'limit' => array( $start, $per_page )
			)
	);

	$this->layout->pages = ceil( count( $this->layout->contacts ) / $per_page );

	$this->layout->content = array( 'script' => 'ajax/list/contacts' );
    }

    /**
     * Elenco Contatti Mini
     */
    private function listContactsMini()
    {
	$this->model_contact = new Classes_Contact();

	list( $orderby_field, $orderby_dir ) = explode( ':', $this->params['orderby'] );

	//
	$per_page = $this->params['per_page']; //rows per page
	$start = ( $this->params['page'] - 1 ) * $per_page;

	$this->layout->contacts = $this->model_contact->fetchAll( array(
		    'orderby' => array( $orderby_field => $orderby_dir ),
		    'limit' => array( $start, $per_page )
			)
	);

	$this->layout->pages = ceil( count( $this->layout->contacts ) / $per_page );

	$this->layout->content = array( 'script' => 'ajax/list/contactsmini' );
    }

    /**
     * Elenco Partners
     */
    private function listPartners()
    {
	$this->model_partner = new Classes_Partner();
        
	list( $orderby_field, $orderby_dir ) = explode( ':', $this->params['orderby'] );

	//
	$per_page = $this->params['per_page']; //rows per page
	$start = ( $this->params['page'] - 1 ) * $per_page;

	$this->layout->partners = $this->model_partner->fetchAll( array(
		    'orderby' => array( $orderby_field => $orderby_dir ),
		    'limit' => array( $start, $per_page )
			)
	);

	$this->layout->pages = ceil( count( $this->layout->partners ) / $per_page );

        $this->layout->partner_types = $this->application->getResource( 'PartnerTypes' );
	$this->layout->content = array( 'script' => 'ajax/list/partners' );
    }

    /**
     * Elenco Partners Mini
     */
    private function listPartnersMini()
    {
	$this->model_partner = new Classes_Partner();
        
	list( $orderby_field, $orderby_dir ) = explode( ':', $this->params['orderby'] );

	//
	$per_page = $this->params['per_page']; //rows per page
	$start = ( $this->params['page'] - 1 ) * $per_page;

	$this->layout->partners = $this->model_partner->fetchAll( array(
		    'orderby' => array( $orderby_field => $orderby_dir ),
		    'limit' => array( $start, $per_page )
			)
	);

	$this->layout->pages = ceil( count( $this->layout->partners ) / $per_page );

        $this->layout->partner_types = $this->application->getResource( 'PartnerTypes' );
	$this->layout->content = array( 'script' => 'ajax/list/partnersmini' );
    }


    /**
     * Elenco Contatti Mini
     */
    private function listArtistsMini()
    {
	$this->model_artist = new Classes_Artist();

	list( $orderby_field, $orderby_dir ) = explode( ':', $this->params['orderby'] );

	//
	$per_page = $this->params['per_page']; //rows per page
	$start = ( $this->params['page'] - 1 ) * $per_page;

	$this->layout->artists = $this->model_artist->fetchAll( array(
		    'orderby' => array( $orderby_field => $orderby_dir ),
		    'limit' => array( $start, $per_page )
			)
	);

	$this->layout->pages = ceil( count( $this->layout->artists ) / $per_page );

	$this->layout->content = array( 'script' => 'ajax/list/artistsmini' );
    }    

    /**
     * Elenco Locations Mini
     */
    private function listLocationsMini()
    {
	$this->model_location = new Classes_Location();

	list( $orderby_field, $orderby_dir ) = explode( ':', $this->params['orderby'] );

	$per_page = $this->params['per_page']; //rows per page
	$start = ( $this->params['page'] - 1 ) * $per_page;

	$this->layout->locations = $this->model_location->fetchAll( array(
		    'orderby' => array( $orderby_field => $orderby_dir ),
		    'limit' => array( $start, $per_page )
			)
	);

	$this->layout->pages = ceil( count( $this->layout->locations ) / $per_page );

	$this->layout->selected = $this->params['selected'];
	$this->layout->content = array( 'script' => 'ajax/list/locationsmini' );
    }    

    /**
     * Elenco Eventi
     */
    private function listEvents()
    {
	$this->model_event = new Classes_Event;

	list( $orderby_field, $orderby_dir ) = explode( ':', $this->params['orderby'] );

	$per_page = $this->params['per_page']; //rows per page
	$start = ( $this->params['page'] - 1 ) * $per_page;

	$this->layout->events = $this->model_event->fetchAll( array(
		    'orderby' => array( $orderby_field => $orderby_dir ),
		    'limit' => array( $start, $per_page )
			)
	);
	
	if( !empty( $this->params['selected'] ) )
	    $selected = explode( ':', $this->params['selected'] );

	$this->layout->pages = ceil( count( $this->layout->events ) / $per_page );

	$this->layout->selected = $selected;
	$this->layout->content = array( 'script' => 'ajax/list/events' );
    }

    /**
     * Elenco Eventi per Tourbook
     */
    private function listTourbooks()
    {
	//$this->model_event      = new Classes_Event;
	$this->model_tourbook   = new Classes_Tourbook;

	list( $orderby_field, $orderby_dir ) = explode( ':', $this->params['orderby'] );

	$per_page = $this->params['per_page']; //rows per page
	$start = ( $this->params['page'] - 1 ) * $per_page;

	$events = $this->model_tourbook->fetchAll( array(
		    'orderby' => array( $orderby_field => $orderby_dir ),
		    'limit' => array( $start, $per_page )//,
                    //'join' => array( 'fab_tourbooks' => array( 'fab_events.event_id', 'fab_tourbooks.tourbook_event_id' ) ),
		)
	);
        
//        foreach( $events AS $event )
//            $tourbooks_id[] = $event['tourbook_id'];
//
//        $tourbooks = $this->model_tourbook->fetchById( $tourbooks_id );
//
//        if( is_array( $tourbooks ) )
//            foreach( $tourbooks as $tourbook )
//                $events[$tourbook['tourbook_event_id']]['tourbook'] = $tourbook;

	if( !empty( $this->params['selected'] ) )
	    $selected = explode( ':', $this->params['selected'] );

	$this->layout->pages    = ceil( count( $this->layout->events ) / $per_page );
        $this->layout->events   = $events;
	$this->layout->selected = $selected;
	$this->layout->content  = array( 'script' => 'ajax/list/tourbooks' );
    }

    /**
     * Elenco Eventi Mini
     */
    private function listEventsMini()
    {
	$this->model_event = new Classes_Event;

	list( $orderby_field, $orderby_dir ) = explode( ':', $this->params['orderby'] );

	$per_page = $this->params['per_page']; //rows per page
	$start = ( $this->params['page'] - 1 ) * $per_page;

	$this->layout->events = $this->model_event->fetchAll( array(
		    'orderby' => array( $orderby_field => $orderby_dir ),
		    'limit' => array( $start, $per_page )
			)
	);

	$this->layout->pages = ceil( count( $this->layout->events ) / $per_page );

	$this->layout->selected = $this->params['selected'];
	$this->layout->content = array( 'script' => 'ajax/list/eventsmini' );
    }

    /**
     * Elenco Live (ad es: Booking)
     */
    private function listLive()
    {
	$this->model_live       = new Classes_Live;
        $this->model_livestatus = new Classes_LiveStatus;
        $this->model_province   = new Classes_Province();

	list( $orderby_field, $orderby_dir ) = explode( ':', $this->params['orderby'] );

	$per_page = $this->params['per_page'] ? $this->params['per_page'] : 50; //rows per page
	$start = ( $this->params['page'] - 1 ) * $per_page;

	$this->layout->live_list = $this->model_live->fetchAll( array(
		    'orderby' => array( $orderby_field => $orderby_dir ),
		    'limit' => array( $start, $per_page )
			)
	);

	$this->layout->pages = ceil( count( $this->layout->live ) / $per_page );

	$this->layout->province = $this->model_province->fetchAll();
        $this->layout->days = $this->getResource( 'Days' );
        $this->layout->months = $this->getResource( 'Months' );
        $this->layout->live_status = $this->model_livestatus->fetchAll();
	$this->layout->selected = $this->params['selected'];
	$this->layout->content = array( 'script' => 'ajax/list/live' );
    }

    /**
     * Elenco Live per Booking
     */
    private function listBookingLive()
    {
	$this->model_live       = new Classes_Live;
        $this->model_livestatus = new Classes_LiveStatus;
        $this->model_province   = new Classes_Province();

	list( $orderby_field, $orderby_dir ) = explode( ':', $this->params['orderby'] );

	$per_page = $this->params['per_page'] ? $this->params['per_page'] : 50; //rows per page
	$start = ( $this->params['page'] - 1 ) * $per_page;

	$this->layout->live_list = $this->model_live->fetchAll( array(
		    'orderby' => array( $orderby_field => $orderby_dir ),
		    'limit' => array( $start, $per_page ),
                    'where' => new Classes_SqlExpression( 'live_date >= CURDATE()' )
			)
	);

	$this->layout->pages = ceil( count( $this->layout->live ) / $per_page );

	$this->layout->province = $this->model_province->fetchAll();
        $this->layout->days = $this->getResource( 'Days' );
        $this->layout->months = $this->getResource( 'Months' );
        $this->layout->live_status = $this->model_livestatus->fetchAll();
        
	$this->layout->content = array( 'script' => 'ajax/list/booking-live' );
    }

    /**
     * Elenco Eventi per Booking
     */
    private function listBookingEvents()
    {
	$this->layout->content = array( 'script' => 'ajax/list/booking-events' );
    }

    /**
     * Elenco Attività per Booking
     */
    private function listBookingActivities()
    {
	$this->layout->content = array( 'script' => 'ajax/list/booking-activities' );
    }
    
    /**
     * Elenchi JSON.
     * Sceglie la sezione in base al parametro 'section' passato da url
     * Eg: /ajax/list/posts/param1/value1/param2/value2 ...
     * 
     * selected è nel formato "/selected/id1:id2:id3"
     * 
     * In generale rimanda a listSezione() per elenchi standard (archivio, rubriche, ecc..
     * e a listSezioneMini per elenchi ridotti (layout a due colonne, ecc..)
     */
    public function jsonAction()
    {

	if( empty( $this->params['section'] ) )
	    throw new Classes_Exceptions( 'Ajax: URL malformato' );

	switch( $this->params['section'] )
	{
	    case 'activities':
		return $this->jsonActivities();
		break;
                
	    default:
		break;
	}
	//sleep(2);
    }    
    
    private function jsonActivities()
    {
        $start  = $this->params['start'];
        $end    = $this->params['end'];
        
	$this->model_activity = new Classes_Activity;

	$activities = $this->model_activity->fetchAll( array(
                    'where' => new Classes_SqlExpression( 'activity_start_date BETWEEN "' . date( 'Y-m-d', $start ) . '" AND "' . date( 'Y-m-d', $end ) .'" OR activity_end_date >= "' . date( 'Y-m-d', $end ) .'"' ),
                    'join' => array( 'fab_users' => array( 'fab_activities.activity_assignedto', 'fab_users.user_id' ) )
			)
	);

        // Suddivide le attività per giorno...
        if( count( $activities ) > 0 )
        {
            foreach( $activities as $activity )
            {
                $start  = $activity['activity_start_date'] . ( !is_null( $activity['activity_start_time'] ) ? 'T'. $activity['activity_start_time'] : '' );
                $end    = $activity['activity_end_date'] . ( !is_null( $activity['activity_end_time'] ) ? 'T'. $activity['activity_end_time'] : '' );
                
//                switch( true )
//                {
//                    case !is_null( $activity['activity_end_date'] ):
//                        $end = ( $activity['activity_end_date'] . ( !is_null( $activity['activity_end_time'] ) ? 'T'. $activity['activity_end_time'] : '' ) );
//                        break;
//
//                    default:
//                        break;
//                }
//                
//                $end    = ( !is_null( $activity['activity_end_date'] )
//                            ? ( $activity['activity_end_date'] . ( !is_null( $activity['activity_end_time'] ) ? 'T'. $activity['activity_end_time'] : '' ) )
//                            : $start );
                
                $ret[] = array(
			'id'            => $activity['activity_id'],
			'title'         => $activity['activity_title'],
			'start'         => $start,
			'end'           => $end,
                        'allDay'        => ( $activity['activity_start_time'] AND $activity['activity_end_time'] ) ? false : true,
                        'desc'          => $activity['activity_description'],
                        'startTimeIta'  => $activity['activity_start_time_ita'],
                        'endTimeIta'    => $activity['activity_end_time_ita'],
                        'url'           => '/admin/attivita/vedi/id/'. $activity['activity_id']
		);
            }
        }
        
        $this->layout->days = $this->getResource( 'Days' );
        $this->layout->months = $this->getResource( 'Months' );
        
        exit( json_encode( $ret ) );
    }


    /**
     * Forms.
     * Sceglie la sezione in base al parametro 'section' passato da url
     * Eg: /ajax/list/posts/param1/value1/param2/value2 ...
     */
    public function formAction()
    {
	if( empty( $this->params['section'] ) )
	    throw new Classes_Exceptions( 'Ajax: URL malformato' );

	switch( $this->params['section'] )
	{
	    case 'newcontact':
		return $this->formNewContact();
		break;

	    case 'newartist':
		return $this->formNewArtist();
		break;

	    case 'newlocation':
		return $this->formNewLocation();
		break;

	    case 'contacts':
		return $this->listContacts();
		break;

	    default:
		break;
	}
	//sleep(2);	 
    }

    private function formNewContact()
    {
	if( $_POST['salva'] AND $_POST['salva'] !== '' )
	{
	    $this->layout->data = $_POST;
	    
	    // Validiamo server-side...
            if( !filter_var( $_POST['contact_firstname'], FILTER_SANITIZE_STRING ) OR !filter_var( $_POST['contact_lastname'], FILTER_SANITIZE_STRING ) )
                $errorMsg['contact_name'] = sprintf( ERR_FORMAT, 'Nome o Cognome' );

            if( !filter_var( $_POST['contact_email'], FILTER_VALIDATE_EMAIL ) )
                $errorMsg['contact_email'] = ERR_EMAIL;

            if( !filter_var( $_POST['contact_phone_prefix'], FILTER_VALIDATE_REGEXP, array( 'options' => array( 'regexp' => "/^[0-9]*$/" ) ) ) OR !filter_var( $_POST['contact_phone_number'], FILTER_VALIDATE_REGEXP, array( 'options' => array( 'regexp' => "/[0-9]*/" ) ) ) )
                $errorMsg['contact_phone'] = sprintf( ERR_FORMAT, 'Tel. Principale' );

	    if( !$errorMsg )
	    {
		// Mapping...
		$data = array(
		    'contact_firstname'		=> ucfirst( $_POST['contact_firstname'] ),
		    'contact_lastname'		=> ucfirst( $_POST['contact_lastname'] ),
		    'contact_email'		=> $_POST['contact_email'],
		    'contact_phone'		=> $_POST['contact_phone_prefix'] .'/'. $_POST['contact_phone_number'],
		    'contact_email2'		=> $_POST['contact_email2'],
		    'contact_email3'		=> $_POST['contact_email3'],
		    'contact_work'		=> $_POST['contact_work_prefix'] .'/'. $_POST['contact_work_number'],
		    'contact_mobile'		=> $_POST['contact_mobile_prefix'] .'/'. $_POST['contact_mobile_number'],
		    'contact_fax'		=> $_POST['contact_fax_prefix'] .'/'. $_POST['contact_fax_number'],
		    'contact_city'		=> $_POST['contact_city'],
		    'contact_cap'		=> $_POST['contact_cap'],
		    'contact_loc'		=> $_POST['contact_loc'],
		    'contact_street'		=> $_POST['contact_street'],
		    'contact_street_number'	=> $_POST['contact_street_number'],
		    'contact_province_id'	=> $_POST['contact_province_id'],		    
		    'contact_notes'		=> $_POST['contact_notes'],		    
		    'contact_createdby'		=> $this->application->auth->user['user_id']
		);
		
		$model = new Classes_Contact( $data );

		if( is_numeric( $contact_id = $model->save()->contact_id ) )
		{
		    return $this->layout->content = array( 'script' => 'ajax/completed' );
		}
		else
		{
		    trigger_error( 'Errore Inserimento Contatto' );
		}
	    }
	}

	$this->layout->errorMsg = $errorMsg;
	$this->layout->content = array( 'script' => 'ajax/form/newcontact' );
    }

    private function formNewArtist()
    {
	if( $_POST['salva'] AND $_POST['salva'] !== '' )
	{
	    $this->layout->data = $_POST;
	    
	    // Validiamo server-side...
	    if( !filter_var( $_POST['artist_name'], FILTER_SANITIZE_STRING ) )
		$errorMsg['artist_name'] = sprintf( ERR_FORMAT, 'Nome Artista' );

	    if( !$errorMsg )
	    {
		// Mapping...
		$data = array(
		    'artist_name'		=> $_POST['artist_name'],
		    'artist_createdby'		=> $this->application->auth->user['user_id']
		);
		
		$model = new Classes_Artist( $data );

		if( is_numeric( $artist_id = $model->save()->artist_id ) )
		{
		    return $this->layout->content = array( 'script' => 'ajax/completed' );
		}
		else
		{
		    trigger_error( 'Errore Inserimento Artista' );
		}
	    }
	}

	$this->layout->errorMsg = $errorMsg;
	$this->layout->content = array( 'script' => 'ajax/form/newartist' );
    }

    private function formNewLocation()
    {
	$this->model_province = new Classes_Province();

	$this->layout->province = $this->model_province->fetchAll();
	
	if( $_POST['salva'] AND $_POST['salva'] !== '' )
	{
	    $this->layout->data = $_POST;
	    
	    // Validiamo server-side...
	    if( !filter_var( $_POST['location_name'], FILTER_SANITIZE_STRING ) )
		$errorMsg['location_name'] = ERR_EMPTY;

	    if( $_POST['location_desc'] != '' AND !filter_var( $_POST['location_desc'], FILTER_SANITIZE_STRING ) )
		$errorMsg['location_desc'] = ERR_EMPTY;

	    if( !filter_var( $_POST['location_street'], FILTER_SANITIZE_STRING ) OR !filter_var( $_POST['location_city'], FILTER_SANITIZE_STRING ) )
		$errorMsg['location_address'] = ERR_EMPTY;

	    if( ( strlen( $_POST['location_cap'] ) != '' ) AND ( strlen( $_POST['location_cap'] ) != 5 OR ( !filter_var( $_POST['location_cap'], FILTER_VALIDATE_INT, array( 'options' => array( 'min_range' => 0, 'max_range' => 98100 ) ) ) ) ) )
		$errorMsg['location_address'] = sprintf( ERR_FORMAT, 'CAP' );


	    if( !$errorMsg )
	    {
		// Mapping...
		$data = array(
		    'location_name'		    => $_POST['location_name'],
		    'location_desc'		    => $_POST['location_desc'],
		    'location_city'		    => $_POST['location_city'],
		    'location_cap'		    => $_POST['location_cap'],
		    'location_loc'		    => $_POST['location_loc'],
		    'location_street'		    => $_POST['location_street'],
		    'location_street_number'	    => $_POST['location_street_number'],
		    'location_province_id'	    => $_POST['location_province_id'],
		    'location_createdby'	    => $this->application->auth->user['user_id'],
		);
		
		$model = new Classes_Location( $data );

		if( is_numeric( $location_id = $model->save()->location_id ) )
		{
		    return $this->layout->content = array( 'script' => 'ajax/completed' );
		}
		else
		{
		    trigger_error( 'Errore Inserimento Location' );
		}
	    }
	}

	$this->layout->errorMsg = $errorMsg;
	$this->layout->content = array( 'script' => 'ajax/form/newlocation' );
    }

     /**
     * Check.
     * Sceglie la sezione in base al parametro 'section' passato da url
     * Eg: /ajax/list/posts/param1/value1/param2/value2 ...
     */   
    public function checkAction()
    {
	if( empty( $this->params['section'] ) )
	    throw new Classes_Exceptions( 'Ajax: URL malformato' );

	switch( $this->params['section'] )
	{
	    case 'contactemail':
		return $this->checkContactEmail();
		break;

	    case 'users':
		return $this->listUsers();
		break;

	    case 'locations':
		return $this->listLocations();
		break;

	    case 'contacts':
		return $this->listContacts();
		break;

	    default:
		break;
	}
	//sleep(2);	 
    }
    
    private function checkContactEmail()
    {
	
    }    
    
    public function uploadAction()
    {
	if( empty( $this->params['section'] ) )
	    throw new Classes_Exceptions( 'Ajax: URL malformato' );

	switch( $this->params['section'] )
	{
	    case 'postimage':
		return $this->uploadPostImage();
		break;

            case 'artistimage':
                return $this->uploadArtistImage();
                break;
            
	    default:
		break;
	}
    }
    
    private function uploadPostImage()
    {
        if( !is_numeric( $post_id = $this->getParam( 'post_id' ) ) )
            exit( '{ "error": "Errore PostId: ' . ( $post_id ) . '" }' );
        
        $uploader = new Classes_Upload( array_shift( $_FILES ) );

        if( $uploader->uploaded )
        {
            // L'immagine è stata caricata correttamente...
            $uploader->allowed = array( 'image/*' );
            $uploader->image_min_width = POST_IMAGE_MIN_WIDTH;
            $uploader->file_safe_name = false;
            $uploader->file_auto_rename = false;
            $uploader->file_overwrite = true;
            $uploader->jpeg_quality = 72;

            if( $uploader->image_src_x > POST_IMAGE_MAX_WIDTH )
            {
                $uploader->image_resize = true;
                $uploader->image_x = POST_IMAGE_MAX_WIDTH;
                $uploader->image_ratio_y = true;
            }

            // Rinomina e carica...
            $uploader->file_new_name_body = 'post_' . $post_id;
            $uploader->process( UPLOAD_DIR . '/temp/' );
            $uploader->clean();

            // Tutto ok?
            if( !$uploader->processed )
            {
                # Aggiungi l'errore
                exit( '{ "error": "' . $uploader->error . '" }' );
            }
        }
        else
        {
            // Aggiungi l'errore
            exit( '{ "error": "' . $uploader->error . '" }' );
        }

        exit( '{ "file_name": "post_'. $post_id .'.'.$uploader->file_dst_name_ext.'" }' );        
    }
    
    private function uploadArtistImage()
    {
        if( !is_numeric( $artist_id = $this->getParam( 'artist_id' ) ) )
            exit( '{ "error": "Errore ArtistId: ' . ( $artist_id ) . '" }' );
        
        $model_artist = new Classes_Artist( array( 'artist_id' => $artist_id ) );
        
        if( !is_numeric( $image_id = $model_artist->uploadImages( $_FILES['artist_image'] ) ) )
        {
            exit( '{ "error": "' . $model_artist->errors . '" }' );
        }
        else
        {
            $model_image = new Classes_ArtistImages;
            $image = array_shift( $model_image->fetchById( array( $image_id ) ) );

            exit( '{ "file_name": "'. $image['artist_image_name'] .'", "image_id" : "'. $image['artist_image_id'] .'" }' );    
        }
        
//        $uploader = new Classes_Upload( array_shift( $_FILES ) );
//
//        if( $uploader->uploaded )
//        {
//            // L'immagine è stata caricata correttamente...
//            $uploader->allowed = array( 'image/*' );
//            $uploader->image_min_width = ARTIST_IMAGE_MIN_WIDTH;
//            //$uploader->file_safe_name = false;
//            //$uploader->file_auto_rename = false;
//            //$uploader->file_overwrite = true;
//            $uploader->jpeg_quality = 72;
//
//            if( $uploader->image_src_x > ARTIST_IMAGE_MAX_WIDTH )
//            {
//                $uploader->image_resize = true;
//                $uploader->image_x = ARTIST_IMAGE_MAX_WIDTH;
//                $uploader->image_ratio_y = true;
//            }
//
//            // Rinomina e carica...
//            $uploader->file_new_name_body = 'artist_' . $artist_id;
//            $uploader->process( UPLOAD_DIR . '/artists/' );
//
//            // Tutto ok?
//            if( !$uploader->processed )
//            {
//                # Aggiungi l'errore
//                exit( '{ "error": "' . $uploader->error . '" }' );
//            }
//        }
//        else
//        {
//            // Aggiungi l'errore
//            exit( '{ "error": "' . $uploader->error . '" }' );
//        }
//
//        $uploader->clean();
//        exit( '{ "file_name": "'. $uploader->file_dst_name .'" }' );        
    }
    
    /**
    * ImagePreview.
    * 
    * Eg: /ajax/imagepreview/param1/value1/param2/value2 ...
    */   
    public function imagePreviewAction()
    {

//         exit('{ "error": "CIAO" }');
    }

    public function removeImageAction()
    {
	if( empty( $this->params['section'] ) )
	    throw new Classes_Exceptions( 'Ajax: URL malformato' );

	switch( $this->params['section'] )
	{
	    case 'artistimage':
		return $this->removeArtistImageAction();
		break;

            case 'artistimage':
                return $this->uploadArtistImage();
                break;
            
	    default:
		break;
	}        
    }
    
    private function removeArtistImageAction()
    {
        $artist_id = $this->getParam( 'id' );
        $image_id = $this->getParam( 'image_id' );
        
        $this->model_artist_images = new Classes_Artist( array( 'artist_id' => $artist_id ) );
        
        if($this->model_artist_images->deleteImages( array($image_id) ))
            echo json_encode( array( 'message' => 'ok' ) );
        else
            echo json_encode( array( 'error' => true ) );
    }

    /**
     * Sceglie la sezione in base al parametro 'section' passato da url
     * Eg: /ajax/add/contactlocation/param1/value1/param2/value2 ... 
     */
    public function addAction()
    {
        if( empty( $this->params['section'] ) )
	    throw new Classes_Exceptions( 'Ajax: URL malformato' );

	switch( $this->params['section'] )
	{
            // Aggiungi le location ai contatti
	    case 'locationtocontact':
		return $this->addLocationToContact();
		break;

            // Aggiungi contatti al partner
	    case 'contacttopartner':
		return $this->addContactToPartner();
		break;

            // Aggiungi contatti alla location
	    case 'contacttolocation':
		return $this->addContactToLocation();
		break;

            // Aggiungi partner al contatto
	    case 'partnertocontact':
		return $this->addPartnerToContact();
		break;
            
            case 'livetoevent':
                return $this->addLiveToEvent();
                break;
        }
    }
    
    private function addLocationToContact()
    {
        $this->contact_roles = $this->application->getResource( 'ContactRoles' );
	$this->layout->contact_roles = $this->contact_roles;
        
        $id = $this->getParam( 'id' );

        $this->model_location = new Classes_Location();

        $this->layout->location = array_shift( $this->model_location->fetchById( array( $id ) ) );
	$this->layout->content = array( 'script' => 'ajax/add/locationtocontact' ); 
    }
    
    private function addContactToPartner()
    {
        $this->contact_roles = $this->application->getResource( 'ContactRoles' );
	$this->layout->contact_roles = $this->contact_roles;
        
        $id = $this->getParam( 'id' );

        $this->model_contact = new Classes_Contact;

        $this->layout->contact = array_shift( $this->model_contact->fetchById( array( $id ) ) );
	$this->layout->content = array( 'script' => 'ajax/add/contacttopartner' ); 
    }
    
    private function addContactToLocation()
    {
        $this->contact_roles = $this->application->getResource( 'ContactRoles' );
	$this->layout->contact_roles = $this->contact_roles;
        
        $id = $this->getParam( 'id' );

        $this->model_contact = new Classes_Contact;

        $this->layout->contact = array_shift( $this->model_contact->fetchById( array( $id ) ) );
	$this->layout->content = array( 'script' => 'ajax/add/contacttolocation' ); 
    }
    
    private function addPartnerToContact()
    {
        $this->layout->contact_roles = $this->application->getResource( 'ContactRoles' );
        $this->layout->partner_types = $this->application->getResource( 'PartnerTypes' );
        
        $id = $this->getParam( 'id' );

        $this->model_partner = new Classes_Partner;

        $this->layout->partner = array_shift( $this->model_partner->fetchById( array( $id ) ) );
	$this->layout->content = array( 'script' => 'ajax/add/partnertocontact' ); 
    }
    
    private function addLiveToEvent()
    {
        $this->layout->contact_roles = $this->application->getResource( 'ContactRoles' );
        $this->layout->partner_types = $this->application->getResource( 'PartnerTypes' );

        $live_id    = $this->getParam( 'live_id' );
        $event_id   = $this->getParam( 'event_id' );

        $this->model_event = new Classes_Event( array( 'event_id' => $event_id ) );

        //$event = array_shift( $this->model_event->fetchById( array( $event_id ) ) );
        $event = array_shift( $this->model_event->fetchById( array( $event_id ) ) );
        
        if( count( $event['live'] ) )
            foreach( $event['live'] as $id => $value )
                $data['live'][] = $value['fab_live_live_id'];
        
        $data['live'][] = $live_id;

        if( !$this->model_event->saveExtra( $data ) )
            echo json_encode( $this->model_event->errors );
            
        $event = array_shift( $this->model_event->fetchById( array( $event_id ) ) );
        
        echo json_encode( array( 'tot' => count( (array) $event['live'] ), 'live' => array_keys( (array) $event['live'] ) ) );
        exit;
    }


    /**
     * Sceglie la sezione in base al parametro 'section' passato da url
     * Eg: /ajax/add/contactlocation/param1/value1/param2/value2 ... 
     */
    public function removeAction()
    {
        if( empty( $this->params['section'] ) )
	    throw new Classes_Exceptions( 'Ajax: URL malformato' );

	switch( $this->params['section'] )
	{
            // Rimuove live da evento...
            case 'livefromevent':
                return $this->removeLiveFromEvent();
                break;
        }
    }    
    
    private function removeLiveFromEvent()
    {
        $live_id    = $this->getParam( 'live_id' );
        $event_id   = $this->getParam( 'event_id' );

        $this->model_event = new Classes_Event( array( 'event_id' => $event_id ) );

        //$event = array_shift( $this->model_event->fetchById( array( $event_id ) ) );
        $event = array_shift( $this->model_event->fetchById( array( $event_id ) ) );
        
        $data['live'] = array();

        unset( $event['live'][$live_id] );
            
        if( count( $event['live'] ) )
            foreach( $event['live'] as $id => $value )
                $data['live'][] = $value['fab_live_live_id'];

        if( !$this->model_event->saveExtra( $data ) )
            echo json_encode( $this->model_event->errors );
            
        $event = array_shift( $this->model_event->fetchById( array( $event_id ) ) );
        
        echo json_encode( array( 'tot' => count( (array) $event['live'] ), 'live' => array_keys( (array) $event['live'] ) ) );
        exit;
    }
    
    /**
      * @todo RIMUOVERE!
     * Select.
     * Sceglie la sezione in base al parametro 'section' passato da url
     * Eg: /ajax/select/posts/param1/value1/param2/value2 ...
     */   
    public function selectAction()
    {
	if( empty( $this->params['section'] ) )
	    throw new Classes_Exceptions( 'Ajax: URL malformato' );

	switch( $this->params['section'] )
	{
            // Aggiungi/rimuovi i contatti alla location
	    case 'addcontactlocation':
		return $this->selectAddContactLocation();
		break;

	    case 'remcontactlocation':
		return $this->selectRemContactLocation();
		break;

            // Aggiungi/rimuovi le location ai contatti
	    case 'addlocationcontact':
		return $this->selectAddLocationContact();
		break;

	    case 'remlocationcontact':
		return $this->selectRemLocationContact();
		break;

	    case 'addcontactpartner':
		return $this->selectAddContactPartner();
		break;

	    case 'remcontactpartner':
		return $this->selectRemContactPartner();
		break;

	    case 'addliveartist':
		return $this->selectAddLiveArtist();
		break;

	    case 'remliveartist':
		return $this->selectRemLiveArtist();
		break;
            
            case 'changelivestatus':
                return $this->selectChangeLiveStatus();
                break;

            case 'events':
                return $this->selectEvents();
                break;

            case 'live':
                return $this->selectLive();
                break;
            
            default:
		break;
	}
	//sleep(2);	 
    }
    
    private function selectAddContactLocation()
    {
        $this->contact_roles = $this->application->getResource( 'ContactRoles' );
	$this->layout->contact_roles = $this->contact_roles;
        
        $id = $this->getParam( 'id' );

        $this->model_contact = new Classes_Contact();

        // Concatena elementi selezionati
	$contacts_ids = ( is_array( $_SESSION['ContactLocation'] ) AND count( $_SESSION['ContactLocation'] ) > 0 ) ? $_SESSION['ContactLocation'] : array();
        $contacts_ids = array_unique( array_merge( $contacts_ids, array( $id ) ) );

        $_SESSION['ContactLocation'] = $contacts_ids;

        $this->layout->contacts = $this->model_contact->fetchById( $contacts_ids );
        
	$this->layout->content = array( 'script' => 'ajax/select/contact-location' );
    }
    
    private function selectRemContactLocation() 
    {
        $this->contact_roles = $this->application->getResource( 'ContactRoles' );
	$this->layout->contact_roles = $this->contact_roles;
        
        $id = $this->getParam( 'id' );

        $this->model_contact = new Classes_Contact();

        // Concatena elementi selezionati
	$contacts_ids = ( is_array( $_SESSION['ContactLocation'] ) AND count( $_SESSION['ContactLocation'] ) > 0 ) ? $_SESSION['ContactLocation'] : array();
        
        foreach( $contacts_ids AS $k => $contact_id )
            if( $contact_id == $id )
                unset( $contacts_ids[$k] );
            
        $_SESSION['ContactLocation'] = $contacts_ids;

        $this->layout->contacts = $this->model_contact->fetchById( $contacts_ids );
        
	$this->layout->content = array( 'script' => 'ajax/select/contact-location' );     
    }
    
    private function selectAddLocationContact()
    {
        $this->contact_roles = $this->application->getResource( 'ContactRoles' );
	$this->layout->contact_roles = $this->contact_roles;
        
        $id = $this->getParam( 'id' );

        $this->model_location = new Classes_Location();

        // Concatena elementi selezionati
	$locations_ids = ( is_array( $_SESSION['LocationContact'] ) AND count( $_SESSION['LocationContact'] ) > 0 ) ? $_SESSION['LocationContact'] : array();
        $locations_ids = array_unique( array_merge( $locations_ids, array( $id ) ) );

        $_SESSION['LocationContact'] = $locations_ids;

        $this->layout->locations = $this->model_location->fetchById( $locations_ids );
        
	$this->layout->content = array( 'script' => 'ajax/select/location-contact' );
    }
    
    private function selectRemLocationContact() 
    {
        $this->contact_roles = $this->application->getResource( 'ContactRoles' );
	$this->layout->contact_roles = $this->contact_roles;
        
        $id = $this->getParam( 'id' );

        $this->model_location = new Classes_Location();

        // Concatena elementi selezionati
	$locations_ids = ( is_array( $_SESSION['LocationContact'] ) AND count( $_SESSION['LocationContact'] ) > 0 ) ? $_SESSION['LocationContact'] : array();
        
        foreach( $locations_ids AS $k => $location_id )
            if( $location_id == $id )
                unset( $locations_ids[$k] );
            
        $_SESSION['LocationContact'] = $locations_ids;

        $this->layout->locations = $this->model_location->fetchById( $locations_ids );
        
	$this->layout->content = array( 'script' => 'ajax/select/location-contact' );    
    }

    private function selectAddContactPartner()
    {
        $this->contact_roles = $this->application->getResource( 'ContactRoles' );
	$this->layout->contact_roles = $this->contact_roles;
        
        $id = $this->getParam( 'id' );

        $this->model_contact = new Classes_Contact();

        // Concatena elementi selezionati
	$contacts_ids = ( is_array( $_SESSION['ContactPartner'] ) AND count( $_SESSION['ContactPartner'] ) > 0 ) ? $_SESSION['ContactPartner'] : array();
        $contacts_ids = array_unique( array_merge( $contacts_ids, array( $id ) ) );

        $_SESSION['ContactPartner'] = $contacts_ids;

        $this->layout->contacts = $this->model_contact->fetchById( $contacts_ids );
        
	$this->layout->content = array( 'script' => 'ajax/select/contact-partner' );
    }
    
    private function selectRemContactPartner() 
    {
        $this->contact_roles = $this->application->getResource( 'ContactRoles' );
	$this->layout->contact_roles = $this->contact_roles;
        
        $id = $this->getParam( 'id' );

        $this->model_contact = new Classes_Contact();

        // Concatena elementi selezionati
	$contacts_ids = ( is_array( $_SESSION['ContactPartner'] ) AND count( $_SESSION['ContactPartner'] ) > 0 ) ? $_SESSION['ContactPartner'] : array();
        
        foreach( $contacts_ids AS $k => $contact_id )
            if( $contact_id == $id )
                unset( $contacts_ids[$k] );
            
        $_SESSION['ContactPartner'] = $contacts_ids;

        $this->layout->contacts = $this->model_contact->fetchById( $contacts_ids );
        
	$this->layout->content = array( 'script' => 'ajax/select/contact-partner' );     
    }

    /**
     * Aggiunge gli id degli artisti selezionati alla sessione
     */
    private function selectAddLiveArtist()
    {
        $id = $this->getParam( 'id' );

        $this->model_artist = new Classes_Artist();
	
	// Se l'artista non è già presente, aggiungi (con info completa)
	if( !array_key_exists( $id, (array) $_SESSION['Live']['Artists'] ) )
	{
	    $_SESSION['Live']['Artists']['main'][$id] = array_shift( $this->model_artist->fetchById( array( $id ) ) );
	}

        $this->layout->artists = $_SESSION['Live']['Artists'];

	$this->layout->content = array( 'script' => 'ajax/select/live-artist' );
    }
    
    private function selectRemLiveArtist() 
    {
        $id = $this->getParam( 'id' );
        
        $this->model_artist = new Classes_Artist();

        // Concatena elementi selezionati
	//$artists_ids = ( is_array( $_SESSION['LiveArtistsId'] ) AND count( $_SESSION['LiveArtistsId'] ) > 0 ) ? $_SESSION['LiveArtistsId'] : array();
        
	unset( $_SESSION['Live']['Artists']['main'][$id] );
	unset( $_SESSION['Live']['Artists']['openingact'][$id] );
	    
        $this->layout->artists = $_SESSION['Live']['Artists'];

	$this->layout->content = array( 'script' => 'ajax/select/live-artist' );     
    }
    
    /**
     * Cambia lo status del live
     */
    private function selectChangeLiveStatus()
    {
        $live_id        = $this->getParam('live_id');
        $live_status    = $this->getParam('live_status_id');
        
        if( is_numeric( $live_id ) AND is_numeric( $live_status ) )
        {
                       
            $model_live = new Classes_Live();
            
            $live = array_shift( $model_live->fetchById( array( $live_id ) ) );
            $model_live->live_id            = $live['live_id'];
            $model_live->live_location_id   = $live['live_location_id'];
            $model_live->live_ispublic      = $live['live_ispublic'];
            $model_live->live_date          = $live['live_date'];
            $model_live->live_createdby     = $live['live_createdby'];
            $model_live->live_status_id     = $live_status;
            $model_live->live_modifiedby    = $this->application->auth->user['user_id'];

            if( is_numeric( $live_id = $model_live->save()->live_id ) )
            {
                exit( json_encode( array( 'live_id' => $live_id ) ) );
                
            }
            else
            {
                exit( json_encode( array( 'errors' => $model_live->errors ) ) );
            }
            
        }
        else
        {
            throw new Exception;
        }
        
        //$this->layout->content = $this->model_live->toArray();     
    }
    
    /**
     * Seleziona Eventi
     */
    private function selectEvents()
    {
	$this->model_event = new Classes_Event;

	list( $orderby_field, $orderby_dir ) = explode( ':', $this->params['orderby'] );

	$per_page = $this->params['per_page']; //rows per page
	$start = ( $this->params['page'] - 1 ) * $per_page;

	$this->layout->events = $this->model_event->fetchAll( array(
		    'orderby' => array( $orderby_field => $orderby_dir ),
		    'limit' => array( $start, $per_page )
			)
	);
	
	if( !empty( $this->params['selected'] ) )
	    $selected = explode( ':', $this->params['selected'] );

	$this->layout->pages = ceil( count( $this->layout->events ) / $per_page );

	$this->layout->selected = $selected;
	$this->layout->content = array( 'script' => 'ajax/select/events' );
    }    
    
    /**
     * Seleziona Live
     */
    private function selectLive()
    {
	$this->model_live       = new Classes_Live;
        $this->model_livestatus = new Classes_LiveStatus;
        $this->model_province   = new Classes_Province();

	list( $orderby_field, $orderby_dir ) = explode( ':', $this->params['orderby'] );

	$per_page = $this->params['per_page'] ? $this->params['per_page'] : 50; //rows per page
	$start = ( $this->params['page'] - 1 ) * $per_page;

	$this->layout->live_list = $this->model_live->fetchAll( array(
		    'orderby' => array( $orderby_field => $orderby_dir ),
		    'limit' => array( $start, $per_page )
			)
	);

	//$this->layout->pages = ceil( count( $this->layout->live ) / $per_page );

	$this->layout->province     = $this->model_province->fetchAll();
        $this->layout->days         = $this->getResource( 'Days' );
        $this->layout->months       = $this->getResource( 'Months' );
        $this->layout->live_status  = $this->model_livestatus->fetchAll();
	//$this->layout->selected     = $this->params['selected'];
	$this->layout->selected     = explode( ',', $this->params['selected'] );
        
//        $this->layout->selected     = json_decode( urldecode( $this->params['selected'] ) );

	$this->layout->content      = array( 'script' => 'ajax/select/live' );
    }    
    
    /**
     * Restituisce l'anteprima dell'immagine..
     */
    private function selectImagePreview()
    {
        $live_id        = $this->getParam('live_id');
        $live_status    = $this->getParam('live_status_id');
        
        if( is_numeric( $live_id ) AND is_numeric( $live_status ) )
        {
                       
            $live = new Classes_Live( array('live_id' => $live_id) );

            $live->live_status_id = $live_status;
            $live->live_modifiedby = $this->application->auth->user['user_id'];
                       
            $live->save();
            
        }
        else
        {
            throw new Exception;
        }
        
        $this->layout->content = $this->model_live->toArray();     
    }

    /**
     * dettagli.
     * Sceglie la sezione in base al parametro 'section' passato da url
     * Eg: /ajax/list/[section]/param1/value1/param2/value2 ...
     * 
     * In generale rimanda a listSezione() per elenchi standard (archivio, rubriche, ecc..
     * e a listSezioneMini per elenchi ridotti (layout a due colonne, ecc..)
     */
    public function detailAction()
    {
	if( empty( $this->params['section'] ) )
	    throw new Classes_Exceptions( 'Ajax: URL malformato' );

	switch( $this->params['section'] )
	{
	    case 'locationcontacts':
		return $this->detailLocationContacts();
		break;

	    default:
		break;
	}
	//sleep(2);
    }
    
    private function detailLocationContacts()
    {
	if( is_null( $this->getParam( 'id' ) ) )
	{
	    trigger_error( 'Errore Vedi Locale' );
	}
	
	$this->model_location	= new Classes_Location();
		
	$this->contact_roles		= $this->application->getResource( 'ContactRoles' );
	$this->layout->contact_roles	= $this->contact_roles;
		
	// Fetch
	$location = $this->model_location->fetchById( array( $this->getParam( 'id' ) ) );

	// Se non c'è lancia l'errore
	if( !is_array( $location ) )
	{
	    trigger_error( 'Errore Vedi Locale', E_USER_WARNING );
	}
	else
	{
	    # Assegniamo i dati al layout
	    $this->layout->data = array_shift( $location );
	}

	$this->layout->content = array( 'script' => 'ajax/detail/location-contacts' );
    }
    
    
     /**
     * Get.
     * Sceglie la sezione in base al parametro 'section' passato da url
     * utilizzato nelle tabbed view
     * Eg: /ajax/get/[section]/param1/value1/param2/value2 ...
     */   
    public function getAction()
    {
	if( empty( $this->params['section'] ) )
	    throw new Classes_Exceptions( 'Ajax: URL malformato' );

	switch( $this->params['section'] )
	{
            case 'video-preview-box':
                $this->layout->id = $this->getParam( 'id' );
                $this->layout->content = array( 'script' => 'ajax/get/video-preview-box' );
                break;
                
	    default:
		break;
	}
	//sleep(2);	 
    }
}